import axios from 'axios'

const state = {
  token: localStorage.getItem('token') || '',
  username: localStorage.getItem('username') || '',
  isAuthenticated: !!localStorage.getItem('token')
}

const mutations = {
  SET_AUTH(state, { token, username }) {
    state.token = token
    state.username = username
    state.isAuthenticated = true
    localStorage.setItem('token', token)
    localStorage.setItem('username', username)
  },
  LOGOUT(state) {
    state.token = ''
    state.username = ''
    state.isAuthenticated = false
    localStorage.removeItem('token')
    localStorage.removeItem('username')
  }
}

const actions = {
  async login({ commit }, credentials) {
    try {
      const response = await axios.post('/api/auth/login', credentials)
      if (response.data.success) {
        commit('SET_AUTH', {
          token: response.data.token,
          username: response.data.username
        })
        return response.data
      } else {
        throw new Error(response.data.message)
      }
    } catch (error) {
      throw error
    }
  },
  
  async logout({ commit }) {
    try {
      const token = localStorage.getItem('token')
      if (token) {
        await axios.post('/api/auth/logout', {}, {
          headers: { Authorization: token }
        })
      }
    } catch (error) {
      console.error('Logout request failed:', error)
    } finally {
      commit('LOGOUT')
    }
  }
}

const getters = {
  isAuthenticated: state => state.isAuthenticated,
  username: state => state.username
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}